<template>
  <div class="container">
    <nav class="navbar">
      <div class="nav-brand" @click="navigateTo('/')">
        <img
          style="height: 70px"
          src="@/assets/Learning.png"
          alt="MindSkip"
          class="logo"
        />
      </div>
      <div class="nav-links">
        <span
          @click="navigateTo('/')"
          :class="['nav-link', { active: isActive('/home') }]"
          style="color: black"
          >首页</span
        >
        <span
          @click="navigateTo('/learning')"
          :class="['nav-link', { active: isActive('/learning') }]"
          style="color: black"
          v-if="
            store.getters.roles.includes('TA') ||
            store.getters.roles.includes('PA') ||
            store.getters.roles.includes('补差') ||
            store.getters.roles.includes('admin')
          "
          >随堂练习</span
        >
        <span
          @click="navigateTo('/simulator')"
          :class="['nav-link', { active: isActive('/simulator') }]"
          style="color: black"
          >模拟器</span
        >
        <span
          @click="navigateTo('/test')"
          :class="['nav-link', { active: isActive('/test') }]"
          style="color: black"
          v-if="
            store.getters.roles.includes('TA') ||
            store.getters.roles.includes('PA') ||
            store.getters.roles.includes('补差') ||
            store.getters.roles.includes('admin')
          "
          >试卷中心
          <span v-if="store.getters.paperCount > 0" class="badge">{{
            store.getters.paperCount
          }}</span>
        </span>
        <span
          @click="navigateTo('/training')"
          :class="['nav-link', { active: isActive('/training') }]"
          style="color: black"
          >培训中心</span
        >
      </div>
      <div class="user-dropdown">
        <button class="dropdown-button" @click="toggleDropdown">
          <img
            :src="avatar"
            alt="暂无头像"
            class="avatar-img"
            @click.stop="promptAvatarChange"
          />
          <i class="arrow-down"></i>
        </button>
        <div class="dropdown-content" v-show="isDropdownOpen">
          <a href="#" @click="updatePassword">修改密码</a>
          <a href="#" @click="handleLogout">退出登录</a>
        </div>
      </div>
    </nav>
    <router-view></router-view>
    <div class="footer">
      <div class="footer-content">
        <p>本网站仅供培训中心内部培训使用，禁止外传与任何商业用途</p>
        <p>Copyright © 2024 All Rights Reserved</p>
      </div>
    </div>
    <el-dialog v-model="showUpload" title="更换头像" width="30%">
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :on-error="handleAvatarError"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-dialog>
    <SetPassword
      :dialogTableVisible="passwordVisible"
      @update:dialogTableVisible="handleUpdate"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import SetPassword from "@/views/login/SetPassword.vue";
import router from "@/router";
import { useStore } from "vuex";
import host from "@/utils/host";
import { getToken } from "@/utils/auth"; // get token from cookie
import { ElMessage, ElMessageBox } from "element-plus";
import questionItemApi from "@/api/questionItem/questionItem";
import { setupWebSocket, closeWebSocket } from "@/utils/websocket";

const store = useStore();
const avatar = computed(() => store.getters.avatar);
const imageUrl = ref("");
const uploadUrl = ref("");

const handleAvatarError = (error) => {
  console.log(error);
};

const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 20000) {
    ElMessage({
      message: "上传成功",
      type: "success",
    });
    imageUrl.value = response.data;
    // 使用 commit 直接触发 mutation
    store.commit("user/SET_AVATAR", imageUrl.value);
  } else {
    ElMessage({
      message: `${response.message}`,
      type: "error",
    });
  }
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("必须是jpg或png格式！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
};

const passwordVisible = ref(false);

const isDropdownOpen = ref(false);

const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value;
};

const handleLogout = async () => {
  // 处理退出登录
  if (!getToken()) {
    //直接返回登陆
    router.push("/login");
    return;
  }
  await store.dispatch("user/logout");
  router.push(`/login?redirect=${router.currentRoute.value.fullPath}`);
};

const updatePassword = () => {
  passwordVisible.value = true;
  console.log(passwordVisible.value);
};

const handleUpdate = (value) => {
  if (value.type === "setPassword") {
    passwordVisible.value = value.val;
  } else {
    console.error("子组件在向父组件传递数据时发生了错误！");
  }
};

const navigateTo = (path) => {
  router.push(path);
};

const isActive = (path) => {
  return router.currentRoute.value.path.includes(path);
};

const getTest = async function () {
  const res = await questionItemApi.getCountByAccount();
  store.dispatch("learn/setPaperCount", res.data);
};

const showUpload = ref(false);

const promptAvatarChange = () => {
  ElMessageBox.confirm(
    '你想要更换头像吗？点击"确定"选择新的头像。',
    "更换头像",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  )
    .then(() => {
      showUpload.value = true;
    })
    .catch((error) => {
      console.log("已取消更换头像", error);
      ElMessage({
        type: "info",
        message: "已取消更换头像",
      });
    });
};

onMounted(() => {
  if (getToken()) {
    let websocket = null;
    websocket = setupWebSocket(getToken());

    // 页面可见性变化的回调方法
    document.addEventListener("visibilitychange", function () {
      if (document.hidden) {
        // 页面被隐藏，关闭 WebSocket 连接
        closeWebSocket();
      } else {
        if (websocket) {
          // 页面可见，重新建立 WebSocket 连接
          websocket = setupWebSocket(getToken());
        }
      }
    });

    getTest();
    // if (store.getters.roles.includes("student")) {
    //   getTest();
    // }
    const token = getToken();
    const port = process.env.NODE_ENV == "development" ? 9080 : 80;
    uploadUrl.value = `http://${host}:${port}/elearning/user/uploadAvatar?token=${token}`;
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  min-width: 95vw;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  height: 70px;
  background-color: rgb(255, 255, 255);
  color: white;
}

.nav-brand {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.logo {
  height: 32px; /* 调整这个值来改变logo大小 */
  width: auto;
}

.nav-links {
  display: flex;
  gap: 1rem;
}

.nav-link {
  text-decoration: none;
  font-size: 16px;
  padding: 0 15px;
  line-height: 50px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.nav-link:hover {
  color: skyblue !important;
  background-color: rgba(255, 255, 255, 0.1);
}

.nav-link.router-link-active {
  color: skyblue !important;
  background-color: rgba(255, 255, 255, 0.1);
}

.nav-link.active {
  color: skyblue !important;
  border-bottom: 2px solid rgb(193, 193, 236);
}

.user-dropdown {
  position: relative;
  margin-left: 20px;
}

.dropdown-button {
  background: none;
  border: none;
  color: white;
  padding: 0 15px;
  cursor: pointer;
  height: 50px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.avatar-img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.arrow-down {
  display: inline-block;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid rgb(47, 6, 6);
  margin-left: 10px;
}

.dropdown-content {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  min-width: 120px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
  z-index: 999;
}

.dropdown-content a {
  color: #333;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  font-size: 14px;
}

.dropdown-content a:hover {
  background-color: #f5f5f5;
}

.main-content {
  margin-top: 50px; /* 与导航栏高度相同 */
  padding: 20px;
}

.badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 15px;
  height: 15px;
  background-color: red;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  position: relative;
  top: -10px;
  right: -5px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.footer {
  background-color: #f5f5f5;
  padding: 20px 0;
  text-align: center;
  margin-top: 30px;
  width: 100%;
}

.footer-content {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.footer-content p {
  margin: 5px 0;
}
</style>
